package com.gmu.filter;

import com.gmu.domain.LoginAdminDetails;
import com.gmu.domain.LoginUserDetails;
import com.gmu.utils.JwtUtil;
import com.gmu.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.security.sasl.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 木鱼~
 * @version 1.0
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){//如果为空放行，后面还有过滤器
            filterChain.doFilter(request,response);
            return;//防止继续向下执行
        }
        //解析token
        String subject = null;
        String role = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            subject = claims.getSubject();
            role = (String) claims.get("role");
        } catch (Exception e) {
            throw new AuthenticationException("token无法解析");
        }
        //通过身份证号从redis中查找token
        String redisKey = "token:"+subject;
        String tokenRedis = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(tokenRedis) || !tokenRedis.equals(token)){
            throw new AuthenticationException("用户未登录");
        }
        if (role.equals("user")){
            //用户每一次请求将更新将loginUserDetails，用户信息存入SecurityContextHolder
            //TODO 获取权限信息封装到Authentication中
            LoginUserDetails loginUserDetails = redisCache.getCacheObject("login:"+subject);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUserDetails,null,loginUserDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }else if (role.equals("admin")){
            LoginAdminDetails loginAdminDetails = redisCache.getCacheObject("loginAdmin:"+subject);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginAdminDetails,null,loginAdminDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }else {
            throw new AuthenticationException("角色有误");
        }
        filterChain.doFilter(request,response);
    }
}
